package com.party.web.jms.listener;

import com.party.common.constant.Constant;
import com.party.web.biz.crowdfund.SupportBizService;
import com.party.web.web.controller.websocket.HandShake;
import org.apache.activemq.command.ActiveMQMapMessage;
import org.apache.activemq.command.ActiveMQMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 退款队列消息监听
 * Created by wei.li
 *
 * @date 2017/5/3 0003
 * @time 11:29
 */
@Component(value = "supportRefundListenerWeb")
public class SupportRefundListener implements javax.jms.MessageListener{

    protected Logger logger = LoggerFactory.getLogger(getClass());

    private ExecutorService threadPool = Executors.newFixedThreadPool(5);

    @Autowired
    private SupportBizService supportBizService;

    public void onMessage(Message message) {
        try {
            if (message instanceof ActiveMQMessage){
                ActiveMQMapMessage mqMessage = (ActiveMQMapMessage) message;
                String id = mqMessage.getString(Constant.TYPE_KEY);
                String memberId = mqMessage.getString(HandShake.CLIENT_ID);
                String sessionId = mqMessage.getString(HandShake.SESSION_ID);
                if (null == memberId || null == sessionId) {
                    supportBizService.refund(id);
                } else {
                    threadPool.execute(() -> {
                        long start = System.currentTimeMillis();
                        supportBizService.refund(id, memberId, sessionId);
                        long end = System.currentTimeMillis();
                        logger.info("web端退款线程:{},supportId:{},执行时间：{}(ms)",Thread.currentThread().getName(),id,(end - start));
                    });
                }
            }
        } catch (JMSException e) {
            logger.error("退款消息队列异常", e);
        }
    }
}
